package com.example.demo.netty.util;

import javax.xml.bind.DatatypeConverter;

/**
 * @ClassName convert
 * @Description 数据类型转换
 * @Company inspur
 * @Author Kevin
 * @Date 2020/7/4 11:12
 * @Version 1.0
 */
public class convert {
    public static final convert INSTANCE = new convert();
    private convert(){};
    //16进制占4位，一个字节8位，所以2byte = 4个16位
    public byte[] numToBytes(int b) {
        String hex = String.format("%04x", b);
        return hexStringToBytes(hex);
    }

    public byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    public byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
    //2个16位
    public byte[] numToHex8(int b) {
        return hexStringToBytes(String.format("%02x", b));
    }

    public static void main(String[] args) {
        byte[] data = INSTANCE.numToBytes(1);
        System.out.println(data.length);
        System.out.println(DatatypeConverter.printHexBinary(data).trim());

    }
}
